package com.pray.praymall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.pray.common.constant.AuthServerConstant;
import com.pray.common.exception.BizCodeEnum;
import com.pray.common.utils.R;
import com.pray.common.vo.MemberResponseVo;
import com.pray.praymall.auth.feign.MemberFeignService;
import com.pray.praymall.auth.feign.ThirdPartyFeignService;
import com.pray.praymall.auth.vo.UserLoginVo;
import com.pray.praymall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * do something
 *
 * @author 魂悸魄
 * @date 2020/9/21 14:25
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService feignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // TODO 1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60秒内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 2、验证码的再次检验。redis，key-phone, value-code   sms:code:15766372150 -> 5565
        String code = UUID.randomUUID().toString().substring(0, 5);
        // redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(),
                10, TimeUnit.MINUTES);
        feignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * // TODO 分布式下的session问题
     * RedirectAttributes：使得重定向可以携带数据
     * 重定向携带数据，利用的是session原理，将数据放在session中。只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉
     *
     * @param vo                 vo
     * @param result             检验结果
     * @param redirectAttributes 重定向携带数据
     * @return 成功返回登录页，失败返回注册页
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，转发到注册页
            return "redirect:http://auth.praymall.com/reg.html";
        }
        // 校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode.split("_")[0])) {
                // 删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码通过
                // 真正注册，调用远程服务进行注册
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.praymall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>(3);
                    errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.praymall.com/reg.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>(3);
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.praymall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>(3);
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，转发到注册页
            return "redirect:http://auth.praymall.com/reg.html";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        // 远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            // 登录成功进入首页，否则回到登录页
            // 设置session
            session.setAttribute(AuthServerConstant.LOGIN_USER, r.getData(new TypeReference<MemberResponseVo>(){}));
            return "redirect:http://praymall.com";
        }
        Map<String, String> errors = new HashMap<>(3);
        errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.praymall.com/login.html";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser == null) {
            // 没登录才需要登录
            return "login";
        }
        return "redirect:http://praymall.com";
    }
}
